<?php

namespace addons\shopro\model;

use app\api\model\LogModel;
use think\Db;
use think\Model;
use addons\shopro\exception\Exception;

/**
 * 优惠券模型
 */
class UserCoupons extends Model
{

    // 表名,不含前缀
    protected $name = 'shopro_user_coupons';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;



    // 追加属性
    protected $append = [

    ];

    public static function send($user_id,$coupons_id,$num)
    {

//        $log = [
//            'user_id' => $user_id,
//            'log' => '19.9轻享产品试用券',
//        ];
//        $log = LogModel::where($log)->find();
//        if($log){
//            return false;
//        }


        $map = [
            'coupons_id' => $coupons_id,
            'user_id' => $user_id,
        ];
        $row = UserCoupons::where($map)->find();
        if($row){
            if ($coupons_id == 1){
                return false;
            }
            $row->coupons_num += $num;
            $row->save();
            return true;
        }

        if ($coupons_id == 1){
            $log = [
                'user_id' => $user_id,
                'date_text' => date('Y-m-d'),
                'log' => '29.9轻享全系正装产品（限一次）',
            ];
            LogModel::create($log);
        }

        $map = [
            'coupons_id' => $coupons_id,
            'user_id' => $user_id,
            'coupons_num' => $num,
            'expiretime' => year_last(),
        ];
        UserCoupons::create($map);
    }

    public static function getText($id)
    {
        $row = self::get($id);
        if($row){
            $c = Coupons::get($row['coupons_id']);
            return $c?$c['name']:'';
        }
        return '';
    }

    public function userCoupons($value, $data)
    {

    }



}
